package com.xzjt.controller;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xzjt.entity.SysUser;
import com.xzjt.service.LoginService;
import com.xzjt.service.SysUserService;
import com.xzjt.utils.JwtUtil;
import com.xzjt.utils.R;
import com.xzjt.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName: LoginController
 * @Author: yuandong
 * @Date 2021/10/9 15:47
 */
@Slf4j
@RestController
public class LoginController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private LoginService loginService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    /**
     * 用户登录
     * @param sysUser
     * @return
     */
    @PostMapping("/login")
    public R<?> login(@RequestBody SysUser sysUser){

        //根据用户名和密码在本地查询用户
        SysUser user = this.sysUserService.selectLoginUser(sysUser);
        if(user==null){
            return R.error("-1","用户不存在");
        }

        //用户生成token(将token-用户信息 存放到redis中)
        String token =loginService.createToken(user);
        if(StringUtils.isBlank(token)){
            log.warn("登录生成token失败");
            return R.error("-1","登录失败");
        }

        JSONObject ret = new JSONObject();
        ret.put("user", user);
        ret.put("token", token);

        return R.ok(ret);
    }


    /**
     * 退出登录
     * @param token
     * @return
     */
    @PostMapping("/logout")
    public R logout(@RequestHeader String token){
        // 从缓存中移除Token
        stringRedisTemplate.opsForValue().getOperations().delete(token);
        return R.ok();
    }








}
